package com.rexolar.openapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rexolar.openapi.bean.request.InactiveGwRequest;
import com.rexolar.openapi.constants.ApiConstant;
import com.rexolar.openapi.db.entity.PaasGatewayCredentials;
import com.rexolar.openapi.db.mapper.GatewayCredentialsMapper;
import com.rexolar.openapi.enums.GwStatusEnum;
import com.rexolar.openapi.service.IGatewayCredentials;
import com.rexolar.openapi.service.RexolarApiClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Slf4j
@Service
public class GatewayCredentialsService extends ServiceImpl<GatewayCredentialsMapper, PaasGatewayCredentials> implements IGatewayCredentials {
    @Autowired
    private GatewayCredentialsMapper gatewayCredentialsMapper;

    @Autowired
    public RexolarApiClient rexolarApiClient;

    public IPage<PaasGatewayCredentials> selectPage(InactiveGwRequest inactiveGwRequest, String tenantId) {
        Page<PaasGatewayCredentials> page = new Page<>(inactiveGwRequest.getPageNo(), inactiveGwRequest.getPageSize());
        LambdaQueryWrapper<PaasGatewayCredentials> queryWrapper = new LambdaQueryWrapper<PaasGatewayCredentials>();
        queryWrapper.eq(PaasGatewayCredentials::getStatus, GwStatusEnum.CREATED.getCode());
        queryWrapper.eq(PaasGatewayCredentials::getTenantId, tenantId);
        queryWrapper.orderByAsc(PaasGatewayCredentials::getGmtCreate);
        return gatewayCredentialsMapper.selectPage(page, queryWrapper);
    }

    @Override
    public boolean permitAllJoin(PaasGatewayCredentials paasGatewayCredentials, String token) {
        HashMap dataMap = new HashMap();
        dataMap.put("Version", "1.0");
        dataMap.put("VendorCode", "Rexense");
        String time = String.valueOf(System.currentTimeMillis());
        dataMap.put("Timestamp", time);
        dataMap.put("Seq", time);
        dataMap.put("DeviceId", paasGatewayCredentials.getClientId());
        dataMap.put("FunctionCode", "PermitAllJoin");
        HashMap payload = new HashMap();
        payload.put("Duration", "120");
        dataMap.put("Payload", payload);
        return rexolarApiClient.updateDeviceAttributes(paasGatewayCredentials.getGwId(), ApiConstant.SHARED_SCOPE, JSON.toJSONString(dataMap), token);
    }
}
